package collections.queue;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * 描述：演示ArrayBlockingQueue的使用
 */

public class ArrayBlockingQueueDemo {
    private final ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(3);

    public static void main(String[] args) {
        ArrayBlockingQueueDemo demo = new ArrayBlockingQueueDemo();
        new Thread(new Interviewer(demo.queue)).start();
        new Thread(new Consumer(demo.queue)).start();
    }

}
class Interviewer implements Runnable {
    private final ArrayBlockingQueue<String> queue;

    public Interviewer(ArrayBlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        System.out.println("10个候选人来参加面试");
        for (int i = 0; i < 10; i++) {
            String candidate = "candidate-" + i;
            try {
                queue.put(candidate);
                System.out.println("安排好了" + candidate);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            queue.put("stop");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class Consumer implements Runnable {
    private final ArrayBlockingQueue<String> queue;

    public Consumer(ArrayBlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            while (true) {
                String candidate = queue.take();
                if (candidate.equals("stop")) {
                    System.out.println("所有候选人都面试完了，结束面试");
                    break;
                }
                System.out.println(candidate + "开始面试");
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
